package com.geek.factory.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.geek.factory.constant.SuccessConstant;
import com.geek.factory.entity.PurchaseReturn;
import com.geek.factory.result.Result;
import com.geek.factory.service.IPurchaseReturnService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 退货单管理控制器
 */
@RestController
@RequestMapping("/purchase-return")
@Api(tags = "后台系统的 - 退货单模块")
@Slf4j
@CrossOrigin
public class PurchaseReturnController {

    @Autowired
    private IPurchaseReturnService purchaseReturnService;

    /**
     * 生成退货单编码
     */
    private String generatePurchaseReturnCodeInternal() {
        String prefix = "PR";  // PR = Purchase Return
        String dateStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String timeStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("HHmmss"));
        return prefix + dateStr + timeStr;
    }

    @ApiOperation("生成退货单编码")
    @GetMapping("/generate-code")
    public Result generatePurchaseReturnCode() {
        try {
            String returnNo = generatePurchaseReturnCodeInternal();
            Map<String, String> result = new HashMap<>();
            result.put("returnNo", returnNo);
            return new Result(SuccessConstant.SUCCESS, "生成成功", result);
        } catch (Exception e) {
            log.error("生成退货单编码失败", e);
            return new Result(SuccessConstant.FAIL, "生成失败");
        }
    }

    @ApiOperation("通过ID查询退货单信息")
    @GetMapping("/{returnId}")
    public Result findPurchaseReturnById(@ApiParam("退货单ID") @PathVariable("returnId") Integer returnId) {
        PurchaseReturn purchaseReturn = purchaseReturnService.getById(returnId);
        log.info("purchaseReturn: {}", purchaseReturn);
        if (purchaseReturn != null) {
            return new Result(SuccessConstant.SUCCESS, "ok", purchaseReturn);
        }
        return new Result(SuccessConstant.FAIL, "退货单不存在");
    }

    // 新增退货单
    @ApiOperation("新增退货单")
    @PostMapping
    public Result addPurchaseReturn(@RequestBody PurchaseReturn purchaseReturn) {
        // 如果没有设置退货单编码，自动生成
        if (purchaseReturn.getReturnNo() == null || purchaseReturn.getReturnNo().trim().isEmpty()) {
            purchaseReturn.setReturnNo(generatePurchaseReturnCodeInternal());
        }

        // 设置默认值
        if (purchaseReturn.getCreatedTime() == null) {
            purchaseReturn.setCreatedTime(LocalDateTime.now());
        }
        if (purchaseReturn.getCreatedBy() == null || purchaseReturn.getCreatedBy().trim().isEmpty()) {
            purchaseReturn.setCreatedBy("admin");
        }

        boolean isSuccess = purchaseReturnService.save(purchaseReturn);
        log.info("新增退货单: {}, 结果: {}", purchaseReturn, isSuccess);
        if (isSuccess) {
            return new Result(SuccessConstant.SUCCESS, "新增成功", purchaseReturn);
        }
        return new Result(SuccessConstant.FAIL, "新增失败");
    }

    // 根据ID删除退货单
    @ApiOperation("根据ID删除退货单")
    @DeleteMapping("/{returnId}")
    public Result deletePurchaseReturn(@ApiParam("退货单ID") @PathVariable("returnId") Integer returnId) {
        boolean isSuccess = purchaseReturnService.removeById(returnId);
        log.info("删除退货单ID: {}, 结果: {}", returnId, isSuccess);
        if (isSuccess) {
            return new Result(SuccessConstant.SUCCESS, "删除成功");
        }
        return new Result(SuccessConstant.FAIL, "删除失败");
    }

    // 修改退货单信息
    @ApiOperation("修改退货单信息")
    @PutMapping("/{returnId}")
    public Result updatePurchaseReturn(@ApiParam("退货单ID") @PathVariable("returnId") Integer returnId, @RequestBody PurchaseReturn purchaseReturn) {
        purchaseReturn.setReturnId(returnId);
        boolean isSuccess = purchaseReturnService.updateById(purchaseReturn);
        log.info("修改退货单: {}, 结果: {}", purchaseReturn, isSuccess);
        if (isSuccess) {
            return new Result(SuccessConstant.SUCCESS, "修改成功", purchaseReturn);
        }
        return new Result(SuccessConstant.FAIL, "修改失败");
    }

    @ApiOperation("分页查询退货单列表")
    @GetMapping("/page")
    public Result getPurchaseReturnPage(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String returnNo,
            @RequestParam(required = false) String supplierName
    ) {
        QueryWrapper<PurchaseReturn> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(returnNo)) {
            wrapper.like("return_no", returnNo);
        }
        if (StringUtils.isNotBlank(supplierName)) {
            wrapper.like("supplier_name", supplierName);
        }
        wrapper.orderByDesc("created_time");

        Page<PurchaseReturn> page = purchaseReturnService.page(new Page<>(current, size), wrapper);
        Map<String, Object> data = new HashMap<>();
        data.put("records", page.getRecords());
        data.put("total", page.getTotal());
        data.put("current", page.getCurrent());
        data.put("size", page.getSize());
        data.put("pages", page.getPages());

        return new Result(SuccessConstant.SUCCESS, "查询成功", data);
    }

    @ApiOperation("获取所有退货单列表")
    @GetMapping("/list")
    public Result getAllPurchaseReturns() {
        List<PurchaseReturn> purchaseReturns = purchaseReturnService.list();
        return new Result(SuccessConstant.SUCCESS, "查询成功", purchaseReturns);
    }
}